package handler

import (
	"chat_08_21/api/request"
	"chat_08_21/internal/model"
	"chat_08_21/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var user model.User

	user.Mobile = req.Mobile

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "手机号已被使用",
			"data":    "",
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.MD5(req.Password),
	}

	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Id,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var user model.User

	user.Mobile = req.Mobile

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登录失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	if user.Password != pkg.MD5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, 24*time.Hour)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登录成功",
		"data":    token,
	})

}
